---
title: "Non-Political Identity Signals"
author: "Levi G. Allen and Wayde Z.C. Marsh"
date: "01/27/26"
output:
  html_document:
    toc: true
    code_folding: hide
  latex_engine: xelatex
  number_sections: yes
mainfont: Helvetica
---

# Setting up the Data {.tabset}

## Loading packages and setting wd

```{r, message = FALSE, warning = FALSE, results ='hide'}

##### Packages #####

library(descr)
library(ggplot2)
library(dplyr)
library(foreign)
library(cjoint)
library(tidyr)
library(splitstackshape)
library(tidyverse)
library(haven)
library(modelsummary)
library(devtools)
devtools::install_version("cregg",version="0.4.0")
library(cregg)

setwd("~/Dropbox/Wayde/Research/Cross-Pressuring")

```

## Load data

```{r}

load('df_cb.Rda') # Study I (conjoint)
load('dat_ces.Rda') # Study II (trad. vignette)
load('dat4_l.Rda') # Study III (conjoint)

```

# Study I

## Conjoint Design Setup

```{r}

attribute_list <- list()

attribute_list[["Education"]] <- c("High School Diploma", "Associates Degree",
                                   "Bachelors Degree", "Graduate Degree")

attribute_list[["Experience"]] <- c("No Prior Political Experience", "City Council",
                                   "County Commissioner", "Mayor", "State Legislator",
                                   "Party Leader in the State Legislature")

attribute_list[["Gender"]] <- c("Female", "Male")

attribute_list[["Race"]] <- c("White", "Asian American",
                                   "Black", "Hispanic", "Mixed Race")

attribute_list[["Religion"]] <- c("United Methodist Church", "Episcopalian",
                                   "Catholic", "Pentecostal",
                                   "Born Again Christian", "Southern Baptist",
                                   "Unitarian/Universalist", "Atheist", "Secular Humanist")

attribute_list[["PID"]] <- c("Independent", "Democrat", "Republican")

attribute_list[["Car.Type"]] <- c("Chevrolet", "Ford",
                                   "BMW", "Subaru", "Toyota")

attribute_list[["Hobbies"]] <- c("Runs Marathons", "NASCAR Fan", "Avid Hunter",
                                   "NBA Fan", "Practices Yoga",
                                   "Plays the Fiddle", "Plays the Violin")

attribute_list[["Occupation"]] <- c("Lawyer", "College Professor", "Teacher",
                                   "Doctor", "Businessperson",
                                   "Farmer", "Electrician")

attribute_list[["Schools"]] <- c("Modest Funding for Charter Schools", 
                                   "Supports Charter",
                                   "Supports Public")

attribute_list[["Global.Warming"]] <- c("Moderate Problem",
                                   "Not a Serious Problem",
                                   "Very Serious Problem")

## Constraints on Randomization

constraint_list <- list()
constraint_list[[1]] <- list()

constraint_list[[1]][["Education"]] <- c("High School Diploma", "Associates Degree",
                                   "Bachelors Degree")
constraint_list[[1]][["Occupation"]] <- c("Lawyer", "College Professor", "Doctor")

design2 <- makeDesign(type='constraints', attribute.levels=attribute_list, constraints=constraint_list)

```

# Conjoing Analysis (cregg)--Marginal Means

```{r}

df_cb <- df_cb[complete.cases(df_cb), ]
df_cb <- subset(df_cb, pid < 2)

m1 <- Chosen ~ Education + Experience + Gender + Race + Religion + PID + Car.Type +
                Hobbies + Occupation + Schools + Global.Warming

p1 <- plot(mm(df_cb, m1, id = ~CaseID), vline = 0.5)
p1_d <- plot(mm(subset(df_cb, party < 0.5), m1, id = ~CaseID), vline = 0.5)
p1_r <- plot(mm(subset(df_cb, party > 0.5), m1, id = ~CaseID), vline = 0.5)

p1; p1_d; p1_r

p1_d <- mm(subset(df_cb, party < 0.5), m1, id = ~CaseID)
p1_r <- mm(subset(df_cb, party > 0.5), m1, id = ~CaseID)

p1_d2 <- mm(subset(df_cb, party < 0.3), m1, id = ~CaseID)
p1_r2 <- mm(subset(df_cb, party > 0.9), m1, id = ~CaseID)

p1_d_interest <- mm(subset(df_cb, party < 0.5 & polinterest > 0.5), m1, id = ~CaseID)
p1_r_interest <- mm(subset(df_cb, party > 0.5 & polinterest > 0.5), m1, id = ~CaseID)
p1_d_nointerest <- mm(subset(df_cb, party < 0.5 & polinterest < 0.5), m1, id = ~CaseID)
p1_r_nointerest <- mm(subset(df_cb, party > 0.5 & polinterest < 0.5), m1, id = ~CaseID)

p1_d$Party <- rep('Democrat', nrow(p1_d))
p1_r$Party <- rep('Republican', nrow(p1_r))

p1_d2$Party <- rep('Democrat', nrow(p1_d2))
p1_r2$Party <- rep('Republican', nrow(p1_r2))

p1_d_interest$Party <- rep('Democrat', nrow(p1_d_interest))
p1_r_interest$Party <- rep('Republican', nrow(p1_r_interest))
p1_d_interest$Interest <- rep('Yes', nrow(p1_d_interest))
p1_r_interest$Interest <- rep('Yes', nrow(p1_r_interest))

p1_d_nointerest$Party <- rep('Democrat', nrow(p1_d_nointerest))
p1_r_nointerest$Party <- rep('Republican', nrow(p1_r_nointerest))
p1_d_nointerest$Interest <- rep('No', nrow(p1_d_nointerest))
p1_r_nointerest$Interest <- rep('No', nrow(p1_r_nointerest))

p1 <- rbind(p1_d, p1_r)
p1_nolean <- rbind(p1_d2, p1_r2)
p1_interest <- rbind(p1_d_interest, p1_r_interest, p1_d_nointerest, p1_r_nointerest)

p_1 <- ggplot(p1, aes(shape = feature)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study I') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_manual(name = 'Attribute', 
                              values = c(0, 1, 2, 4, 5, 16, 3, 15, 12, 10, 17)) +
          theme(text=element_text(family="serif"))

p_1_nolean <- ggplot(p1_nolean, aes(shape = feature)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study I') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_manual(name = 'Attribute', 
                              values = c(0, 1, 2, 4, 5, 16, 3, 15, 12, 10, 17)) +
          theme(text=element_text(family="serif"))

p_1_interest <- ggplot(p1_interest, aes(shape = feature, color = Interest)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study I') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_manual(name = 'Attribute', 
                              values = c(0, 1, 2, 4, 5, 16, 3, 15, 12, 10, 17)) +
          theme(text=element_text(family="serif"))

# ggsave('p1_mm.png', p_1, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring', width = 200, height = 190, units = 'mm')

# ggsave('p1.png', p1, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 190, units = 'mm')
# ggsave('p1_d.png', p1_d, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 190, units = 'mm')
# ggsave('p1_r.png', p1_r, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 190, units = 'mm')

# ggsave('p1_nolean.png', p_1_nolean, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 190, units = 'mm')
# ggsave('p1_interest.png', p_1_interest, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 190, units = 'mm')

```


# Study II: Traditional Survey Experiment

```{r}

#setwd("~/Dropbox/Wayde/Research/Cross-Pressuring")

dat3$treat <- dat3$UND478
# 1 = control, 2 = GOP control, 3 = no PID, conservative,
# 4 = no PID, liberal, 5 = GOP, conservative, 6 = GOP, liberal

dat3$dv <- dat3$UND479

dat3$dv_ft <- dat3$UND481

dat3$party <- dat3$UND482
dat3 <- as.data.frame(dat3)

dat3$gop <- ifelse(dat3$pid7 < 4, 0,
            ifelse(dat3$pid7 > 4 & dat3$pid7 < 8, 1, NA))
dat3$gop_nolean <- ifelse(dat3$pid7 < 3, 0,
                   ifelse((dat3$pid7 == 6 | dat3$pid7 == 7), 1, NA))

dat3$polinterest <- ifelse((dat3$newsint == 1 | dat3$newsint == 2), 1,
                ifelse((dat3$newsint == 3 | dat3$newsint == 4), 0, NA))

m1 <- lm(dv_ft ~ as.factor(treat) + polinterest,
         data = dat3)
summary(m1)

m2 <- lm(dv_ft ~ as.factor(treat)*gop + polinterest,
         data = dat3)
summary(m2)

m1_dem <- lm(dv_ft ~ as.factor(treat) + polinterest,
         data = subset(dat3, gop == 0))
summary(m1_dem)

m1_gop <- lm(dv_ft ~ as.factor(treat) + polinterest,
         data = subset(dat3, gop == 1))
summary(m1_gop)

m1_dem_no <- lm(dv_ft ~ as.factor(treat) + polinterest,
         data = subset(dat3, gop_nolean == 0))
summary(m1_dem_no)

m1_gop_no <- lm(dv_ft ~ as.factor(treat) + polinterest,
         data = subset(dat3, gop_nolean == 1))
summary(m1_gop_no)

modelsummary(models = list('Full Sample'  = m1,
                           'Democrats' = m1_dem,
                           'Republicans' = m1_gop,
                           'Democrats, No Leaners' = m1_dem_no,
                           'Republicans, No Leaners' = m1_gop_no),
             output = 'latex',
             stars = c('*' = .05),
             gof_omit = 'AIC|BIC|F|RMSE|Log.Lik.',
             escape = FALSE)

```

## Figures for Study II

```{r}

coef1 <- c(m1_dem$coefficients[2:6], m1_gop$coefficients[2:6])
se1 <- sqrt(diag(vcov(m1_dem))); se2 <- sqrt(diag(vcov(m1_gop)))

hi1 <- c(coef1[1]+(1.96*se1[2]), coef1[2]+(1.96*se1[3]),
            coef1[3]+(1.96*se1[4]), coef1[4]+(1.96*se1[5]),
            coef1[5]+(1.96*se1[6]),
         coef1[6]+(1.96*se2[2]), coef1[7]+(1.96*se2[3]),
            coef1[8]+(1.96*se2[4]), coef1[9]+(1.96*se2[5]),
            coef1[10]+(1.96*se2[6]))

lo1 <- c(coef1[1]-(1.96*se1[2]), coef1[2]-(1.96*se1[3]),
            coef1[3]-(1.96*se1[4]), coef1[4]-(1.96*se1[5]),
            coef1[5]-(1.96*se1[6]),
         coef1[6]-(1.96*se2[2]), coef1[7]-(1.96*se2[3]),
            coef1[8]-(1.96*se2[4]), coef1[9]-(1.96*se2[5]),
            coef1[10]-(1.96*se2[6]))

party <- c('Democratic', 'Democratic', 'Democratic', 'Democratic', 'Democratic', 'Republican', 'Republican', 'Republican', 'Republican',
               'Republican')
tr <- rep(c('eRepublican',
            'dNon-Political Republican',
            'cNon-Political Democrat',
            'bRepublican, Non-Political Republican',
            'aRepublican, Non-Political Democrat'), 4)

df_1 <- as.data.frame(cbind(coef1, hi1, lo1, party, tr))
df_1[, 1:3] <- lapply(df_1[, 1:3], as.numeric)
df_1[, 4:5] <- lapply(df_1[, 4:5], as.factor)

plot1 <- ggplot(df_1, aes(shape = party)) +
  theme_bw() +
  geom_vline(xintercept = 0, linetype = 'dashed') +
  geom_pointrange(aes(x = coef1, y = tr, xmin = lo1,
                         xmax = hi1),
                     lwd = 1, position = position_dodge(width = 0.5), fill = 'WHITE') +
  # xlim(-20, 50) +
  scale_shape_manual(name = 'Partisanship',
                    labels = c('Democrats', 'Republicans'),
                    values = c(15, 1)) +
  scale_y_discrete(name = 'Treatment Condition',
                   labels = c('Republican, Non-Political Democrat',
                              'Republican, Non-Political Republican',
                              'Non-Political Democrat',
                              'Non-Political Republican',
                              'Republican')) +
  scale_x_continuous("Estimated Effect on Candidate Support") +
  labs(title = 'Partisans Are Attentive to Non-Political Partisan Signals') +
       # caption = '\nNote: Estimated effects were calculated from two separate models (based on partisan identity). \nError bars represent 95/% confidence intervals. Full results table in Appendix E.') +
  theme(axis.text=element_text(size = 10)) + 
  theme(plot.title = element_text(hjust = 0.5)) + 
  theme(plot.caption = element_text(hjust = 0)) +
  theme(text=element_text(size = 10, family="serif"))

plot1

# ggsave('plot1_trad.png', plot1, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 127, units = 'mm')

```

# Study III

## Marginal Means

```{r}

dat4_l <- dat4_l[complete.cases(dat4_l), ]

names(dat4_l) <- c('CaseID', 'PID', 'choice', 'rank1', 'rank2', 'why', 'Party', 'Pipeline', 'Hobbies', 'Car', 'Restaurant', 'contest_no', 'profile')

dat4_l$Party <- as.factor(dat4_l$Party)
dat4_l$Party = relevel(dat4_l$Party, ref = 'Independent')

dat4_l$choice2 <- ifelse(dat4_l$choice == 'Candidate A', 0, 1)

m4 <- choice2 ~ Party + Pipeline + Hobbies + Car + Restaurant

p4 <- plot(mm(dat4_l, m4, id = ~CaseID), vline = 0.5)
p4_d <- plot(mm(subset(dat4_l, PID < 3), m4, id = ~CaseID), xlab = 'Marginal Mean', vline = 0.5)
p4_r <- plot(mm(subset(dat4_l, PID > 3), m4, id = ~CaseID), xlab = 'Marginal Mean', vline = 0.5)

p4_d <- mm(subset(dat4_l, PID < 3), m4, id = ~CaseID)
p4_r <- mm(subset(dat4_l, PID > 3), m4, id = ~CaseID)

p4_d$Party <- rep('Democrat', nrow(p4_d))
p4_r$Party <- rep('Republican', nrow(p4_r))

p4 <- rbind(p4_d, p4_r)

p_4 <- ggplot(p4, aes(shape = feature)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study IV') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_discrete(name = "Attribute") +
          theme(text=element_text(family="serif"))

# ggsave('p4_mm.png', p_4, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring', width = 200, height = 150, units = 'mm')

# ggsave('p4.png', p4, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 190, units = 'mm')
# ggsave('p4_d.png', p4_d, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 190, units = 'mm')
# ggsave('p4_r.png', p4_r, 'png', '~/Dropbox/Wayde/Research/Cross-Pressuring',
#     width = 190, height = 190, units = 'mm')

## strong partisans

p4_sd <- mm(subset(dat4_l, PID == 0), m4, id = ~CaseID)
p4_sr <- mm(subset(dat4_l, PID == 6), m4, id = ~CaseID)

p4_sd$Party <- rep('Democrat', nrow(p4_sd))
p4_sr$Party <- rep('Republican', nrow(p4_sr))

p4s <- rbind(p4_sd, p4_sr)

p_4s <- ggplot(p4s, aes(shape = feature)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study IV') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_discrete(name = "Attribute") +
          theme(text=element_text(family="serif"))

# ggsave('p4s_mm.png', p_4s, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin', width = 200, height = 150, units = 'mm')

```

## AMCE

```{r}

results4_d <- cjoint::amce(choice2 ~ Party + Pipeline + Hobbies + Car + Restaurant,
                data = subset(dat4_l, PID < 3), respondent.id = "CaseID")
results4_r <- cjoint::amce(choice2 ~ Party + Pipeline + Hobbies + Car + Restaurant,
                data = subset(dat4_l, PID > 3), respondent.id = "CaseID")
summary(results4_d); summary(results4_r)

p4_d_amce <- plot.amce(results4_d, xlab="Change in Pr(Vote for Candidate) among Democrats",
          ci = 0.95,
          xlim = c(-0.3, 0.3),
          breaks = c(-0.2, 0, 0.2),
          labels = c("-.2","0",".2"),
          # attribute.names = c('Car Type', 'Hobbies', 'PID', 'Pipeline', 'Restaurant'),
          text.size = 9,
          point.size = 0.4,
          dodge.size = 0.9,
          font.family = 'serif')
p4_r_amce <- plot.amce(results4_r, xlab="Change in Pr(Vote for Candidate) among Republicans",
          ci = 0.95,
          xlim = c(-0.3, 0.3),
          breaks = c(-0.2, 0, 0.2),
          labels = c("-.2","0",".2"),
          # attribute.names = c('Car Type', 'Hobbies', 'PID', 'Pipeline', 'Restaurant'),
          text.size = 9,
          point.size = 0.4,
          dodge.size = 0.9,
          font.family = 'serif')

# ggsave('p4_d_amce.png', p4_d_amce, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin_SI', width = 200, height = 190, units = 'mm')
# ggsave('p4_r_amce.png', p4_r_amce, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin_SI', width = 200, height = 190, units = 'mm')

```

# Congruence and Match Analysis

Study I

PolMatch: Rep+Not serious problem+charter schools or Dem+serious problem+public schools
NonPolMatch: NASCAR+Ford+Chick-fil-a or Violin+Subaru+Starbucks
TotalMatch: Rep+Pro-Pipeline+NASCAR+Ford+Chick-fil-a or Dem+Pro-Environment+Violin+Subaru+Starbucks

Study III

PolMatch: Rep+Pro-Pipeline or Dem+Pro-Environment
NonPolMatch: NASCAR+F-150+Chick-fil-a or NBA+Prius+Starbucks
TotalMatch: Rep+Pro-Pipeline+NASCAR+F-150+Chick-fil-a or Dem+Pro-Environment+NBA+Prius+Starbucks

## Study I

```{r}

df_cb$Congruence <- ifelse((df_cb$PID == 'Republican' & (df_cb$Schools == 'Supports Charter' & df_cb$Global.Warming == 'Not a Serious Problem')) | 
                           (df_cb$PID == 'Democrat' & (df_cb$Schools == 'Supports Public' & df_cb$Global.Warming == 'Very Serious Problem')), 'PolCong',
        ifelse((df_cb$Hobbies == 'NASCAR Fan' & df_cb$Car.Type == 'Ford') | 
               (df_cb$Hobbies == 'NBA Fan' & df_cb$Car.Type == 'Subaru'), 'NonPolCong',
        ifelse(df_cb$PID == 'Republican' & (df_cb$Schools == 'Supports Charter' & df_cb$Global.Warming == 'Not a Serious Problem') & 
                  (df_cb$Hobbies == 'NASCAR Fan' & df_cb$Car.Type == 'Ford') | df_cb$PID == 'Democrat' & (df_cb$Schools == 'Supports Public' & df_cb$Global.Warming == 'Very Serious Problem') & (df_cb$Hobbies == 'NBA Fan' & df_cb$Car.Type == 'Subaru'), 'TotalCong', 'NoCong')))

df_cb$Match <- ifelse((df_cb$pid > 0.5 & (df_cb$PID == 'Republican' & (df_cb$Schools == 'Supports Charter' & df_cb$Global.Warming == 'Not a Serious Problem'))) | (df_cb$pid < 0.5 & (df_cb$PID == 'Democrat' & (df_cb$Schools == 'Supports Public' & df_cb$Global.Warming == 'Very Serious Problem'))), 'PolMatch',
        ifelse((df_cb$pid > 0.5 & (df_cb$Hobbies == 'NASCAR Fan' & df_cb$Car.Type == 'Ford')) | (df_cb$pid < 0.5 & (df_cb$Hobbies == 'NBA Fan' & df_cb$Car.Type == 'Subaru')), 'NonPolMatch', 'NoMatch'))

df_cb$Congruence <- as.factor(df_cb$Congruence)
df_cb$Match <- as.factor(df_cb$Match)

df_cb <- df_cb[complete.cases(df_cb), ]

m1 <- Chosen ~ Education + Experience + Gender + Race + Religion + PID + Car.Type + Hobbies + Occupation + Schools + Global.Warming + Match

p1_d <- mm(subset(df_cb, party < 0.5), m1, id = ~CaseID)
p1_r <- mm(subset(df_cb, party > 0.5), m1, id = ~CaseID)

p1_d$Party <- rep('Democrat', nrow(p1_d))
p1_r$Party <- rep('Republican', nrow(p1_r))

p1 <- rbind(p1_d, p1_r)

p_1_cong <- ggplot(p1, aes(shape = feature)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study I') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_manual(name = 'Attribute', 
                              values = c(0, 1, 2, 4, 5, 16, 3, 15, 12, 10, 17, 8)) +
          theme(text=element_text(family="serif"))

# ggsave('p1_cong.png', p_1_cong, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin', width = 200, height = 190, units = 'mm')

p_1_match <- ggplot(p1, aes(shape = feature)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study I') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_manual(name = 'Attribute', 
                              values = c(0, 1, 2, 4, 5, 16, 3, 15, 12, 10, 17, 8)) +
          theme(text=element_text(family="serif"))

# ggsave('p1_match.png', p_1_match, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin', width = 200, height = 190, units = 'mm')

```

## Study III

```{r}

dat4_l$Congruence <- ifelse((dat4_l$Party == 'Republican' & dat4_l$Pipeline == 'Pro-Pipeline') | (dat4_l$Party == 'Democrat' & dat4_l$Pipeline == 'Pro-Environment'), 'PolCong',
        ifelse((dat4_l$Hobbies == 'NASCAR Fan' & (dat4_l$Car == 'F-150' & dat4_l$Restaurant == 'Chick-fil-a')) | 
               (dat4_l$Hobbies == 'NBA Fan' & (dat4_l$Car == 'Prius' & dat4_l$Restaurant == 'Starbucks')), 'NonPolCong',
        ifelse((dat4_l$Party == 'Republican' & dat4_l$Pipeline == 'Pro-Pipeline') & 
                 (dat4_l$Hobbies == 'NASCAR Fan' & (dat4_l$Car == 'F-150' & dat4_l$Restaurant == 'Chick-fil-a')) | (dat4_l$Party == 'Democrat' & dat4_l$Pipeline == 'Pro-Environment') & 
                 (dat4_l$Hobbies == 'NBA Fan' & (dat4_l$Car == 'Prius' & dat4_l$Restaurant == 'Starbucks')), 'TotalCong', 'NoCong')))

dat4_l$Congruence <- as.factor(dat4_l$Congruence)

dat4_l$Match <- ifelse((dat4_l$PID > 3 & (dat4_l$Party == 'Republican' & dat4_l$Pipeline == 'Pro-Pipeline')) | (dat4_l$PID < 3 & (dat4_l$Party == 'Democrat' & dat4_l$Pipeline == 'Pro-Environment')), 'PolMatch',
        ifelse((dat4_l$PID > 3 & (dat4_l$Hobbies == 'NASCAR Fan' & (dat4_l$Car == 'F-150' & dat4_l$Restaurant == 'Chick-fil-a'))) | 
               (dat4_l$PID < 3 & (dat4_l$Hobbies == 'NBA Fan' & (dat4_l$Car == 'Prius' & dat4_l$Restaurant == 'Starbucks'))), 'NonPolMatch', 'NoMatch'))

dat4_l$Match <- as.factor(dat4_l$Match)

dat4_l <- dat4_l[complete.cases(dat4_l), ]

names(dat4_l) <- c('CaseID', 'PID', 'choice', 'rank1', 'rank2', 'why', 'Party', 'Pipeline', 'Hobbies', 'Car', 'Restaurant', 'contest_no', 'profile', 'choice2', 'Congruence', 'Match')

dat4_l$Party <- as.factor(dat4_l$Party)
dat4_l$Party = relevel(dat4_l$Party, ref = 'Independent')

dat4_l$choice2 <- ifelse(dat4_l$choice == 'Candidate A', 0, 1)

m4 <- choice2 ~ Party + Pipeline + Hobbies + Car + Restaurant + Match

p4_d <- mm(subset(dat4_l, PID < 3), m4, id = ~CaseID)
p4_r <- mm(subset(dat4_l, PID > 3), m4, id = ~CaseID)

p4_d$Party <- rep('Democrat', nrow(p4_d))
p4_r$Party <- rep('Republican', nrow(p4_r))

p4 <- rbind(p4_d, p4_r)

p_4_cong <- ggplot(p4, aes(shape = feature)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study IV') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_discrete(name = "Attribute") +
          theme(text=element_text(family="serif"))

# ggsave('p4_cong.png', p_4_cong, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin', width = 200, height = 190, units = 'mm')

p_4_match <- ggplot(p4, aes(shape = feature)) +
          geom_hline(yintercept = 0.5, colour = gray(1/2), lty = 2) +
          facet_wrap(Party ~ .) +
          geom_pointrange(aes(x = level, y = estimate, 
                            ymin = lower, 
                            ymax = upper), 
                            lwd = 1/2, position = position_dodge(width = 1/2),
                           fill = "WHITE") +
          coord_flip() + theme_bw() +
          # ggtitle('Study IV') +
          theme(plot.title = element_text(hjust = 0.5)) +
          xlab('Attribute Level') + ylab('Marginal Mean') +
          scale_shape_discrete(name = "Attribute") +
          theme(text=element_text(family="serif"))

# ggsave('p4_match.png', p_4_match, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin', width = 200, height = 190, units = 'mm')

```

# Cleaned SI

```{r Cleaned SI Code}

df_cb$party1 <- ifelse(df_cb$party > 0.5, 'Republican',
                       ifelse(df_cb$party < 0.5, 'Democrat', NA))
df_cb$party1 <- as.factor(df_cb$party1)

study1 <- cj(
  df_cb, 
  m1, 
  id = ~CaseID, 
  estimate = "mm_diff", 
  by = ~party1
)

p1_party <- study1 %>% 
  as_tibble() %>% 
  # mutate(estimate_nice = case_when(
  #   estimate != 0 ~ label_percent()(estimate),
  #   estimate == 0 ~ NA
  # )) %>% 
  ggplot(aes(x = estimate, y = level, color = party1)) +
  geom_vline(xintercept = 0.5) +
  geom_pointrange(aes(xmin = lower, xmax = upper)) +
  geom_label(
    aes(label = estimate),
    position = position_dodge(width = -1.2),
    size = 3.5, show.legend = FALSE
  ) +
  # scale_x_continuous(labels = label_percent()) +
  # scale_color_manual(values = party1) +
  labs(
    x = "Marginal means",
    y = NULL,
    color = NULL,
    title = "Marginal means by respondent party"
  ) +
  facet_wrap(~feature, ncol = 1) +
  theme(
    legend.position = "bottom",
    legend.justification = "left",
    legend.margin = margin(l = -7, t = -5)
  )

```

# Conjoint ANOVA: Nested Model Comparison Tests

```{r}

# Study I

s1 <- cj_anova(df_cb, m1, by = ~CaseID)

## Study III

s4 <- cj_anova(dat4_l, m4, by = ~CaseID)


```

# Diagnostics

```{r}

## Frequencies/Proportions

s1_freq <- plot(cj_freqs(df_cb, m1, id = ~CaseID))
s4_freq <- plot(cj_freqs(dat4_l, m4, id = ~CaseID))

s1_props <- subset(cj_props(df_cb, ~Occupation + Education, id = ~CaseID), Proportion == 0)


# ggsave('s1_freq.png', s1_freq, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin', width = 200, height = 150, units = 'mm')
# 
# ggsave('s4_freq.png', s4_freq, 'png', '~/Dropbox/Wayde/Research/Apps/Overleaf/FiddleViolin', width = 200, height = 150, units = 'mm')

## Balance Testing

p_1b <- plot(mm(df_cb, gop_mov ~ Education + Experience + Gender + Race + Religion + PID + Car.Type + Hobbies + Occupation + Schools + Global.Warming, id = ~CaseID), vline = mean(df_cb$gop_mov, na.rm = T))

```

# Tables

```{r}

library(knitr)
library(kableExtra)

# Marginal Means

## Study I

p1_df <- as.data.frame(cbind(round(p1_d$estimate, digits = 3), round(p1_d$std.error, digits = 3), round(p1_r$estimate, digits = 3), round(p1_r$std.error, digits = 3)))

p1_df$level <- p1_d$level

names(p1_df) <- c('Estimate.D', 'SE.D', 'Estimate.R', 'SE.R', 'Level')

p1_df <- p1_df[, c(5, 1:4)]

p1_tab <- kable(p1_df, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1, "Democrats" = 2, "Republicans" = 2)) %>%
  pack_rows("Education", 1, 4) %>%
  pack_rows("Political Experience", 5, 10) %>%
  pack_rows("Sex", 11, 12) %>%
  pack_rows("Race", 13, 17) %>%
  pack_rows("Religion", 18, 26) %>%
  pack_rows("Party Affiliation", 27, 29) %>%
  pack_rows("Car", 30, 34) %>%
  pack_rows("Hobbies", 35, 41) %>%
  pack_rows("Occupation", 42, 48) %>%
  pack_rows("Education Policy", 49, 51) %>%
  pack_rows("Global Warming", 52, 54)

## Study III

p4_df <- as.data.frame(cbind(round(p4_d$estimate, digits = 3), round(p4_d$std.error, digits = 3), round(p4_r$estimate, digits = 3), round(p4_r$std.error, digits = 3)))

p4_df$level <- p4_d$level

names(p4_df) <- c('Estimate.D', 'SE.D', 'Estimate.R', 'SE.R', 'Level')

p4_df <- p4_df[, c(5, 1:4)]

p4_tab <- kable(p4_df, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1, "Democrats" = 2, "Republicans" = 2)) %>%
  pack_rows("Party Affiliation", 1, 3) %>%
  pack_rows("Pipeline Stance", 4, 6) %>%
  pack_rows("Hobbies", 7, 9) %>%
  pack_rows("Car", 10, 12) %>%
  pack_rows("Restaurant", 13, 15)

# AMCEs

p1_d_amce <- amce(subset(df_cb, party < 0.5), m1, id = ~CaseID)
p1_r_amce <- amce(subset(df_cb, party > 0.5), m1, id = ~CaseID)

p4_d_amce <- amce(subset(dat4_l, PID < 3), m4, id = ~CaseID)
p4_r_amce <- amce(subset(dat4_l, PID > 3), m4, id = ~CaseID)

## Study I

p1_df_amce <- as.data.frame(cbind(round(p1_d_amce$estimate, digits = 3), round(p1_d_amce$std.error, digits = 3), round(p1_r_amce$estimate, digits = 3), round(p1_r_amce$std.error, digits = 3)))

p1_df_amce$level <- p1_d_amce$level

names(p1_df_amce) <- c('Estimate.D', 'SE.D', 'Estimate.R', 'SE.R', 'Level')

p1_df_amce <- p1_df_amce[, c(5, 1:4)]

p1_tab_amce <- kable(p1_df_amce, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1, "Democrats" = 2, "Republicans" = 2)) %>%
  pack_rows("Education", 1, 4) %>%
  pack_rows("Political Experience", 5, 10) %>%
  pack_rows("Sex", 11, 12) %>%
  pack_rows("Race", 13, 17) %>%
  pack_rows("Religion", 18, 26) %>%
  pack_rows("Party Affiliation", 27, 29) %>%
  pack_rows("Car", 30, 34) %>%
  pack_rows("Hobbies", 35, 41) %>%
  pack_rows("Occupation", 42, 48) %>%
  pack_rows("Education Policy", 49, 51) %>%
  pack_rows("Global Warming", 52, 54)

## Study III

p4_df_amce <- as.data.frame(cbind(round(p4_d_amce$estimate, digits = 3), round(p4_d_amce$std.error, digits = 3), round(p4_r_amce$estimate, digits = 3), round(p4_r_amce$std.error, digits = 3)))

p4_df_amce$level <- p4_d_amce$level

names(p4_df_amce) <- c('Estimate.D', 'SE.D', 'Estimate.R', 'SE.R', 'Level')

p4_df_amce <- p4_df_amce[, c(5, 1:4)]

p4_tab_amce <- kable(p4_df_amce, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1, "Democrats" = 2, "Republicans" = 2)) %>%
  pack_rows("Party Affiliation", 1, 3) %>%
  pack_rows("Pipeline Stance", 4, 6) %>%
  pack_rows("Hobbies", 7, 9) %>%
  pack_rows("Car", 10, 12) %>%
  pack_rows("Restaurant", 13, 15)

## Subsets

p1_all_amce <- amce(df_cb, m1, id = ~CaseID)
p1_female_amce <- amce(subset(df_cb, female == 1), m1, id = ~CaseID)
p1_male_amce <- amce(subset(df_cb, female == 0), m1, id = ~CaseID)
p1_rural_amce <- amce(subset(df_cb, rural > 0.3), m1, id = ~CaseID)
p1_urban_amce <- amce(subset(df_cb, rural < 0.4), m1, id = ~CaseID)

p4_all <- mm(dat4_l, m4, id = ~CaseID)
p4_sd <- mm(subset(dat4_l, PID == 0), m4, id = ~CaseID)
p4_sr <- mm(subset(dat4_l, PID == 6), m4, id = ~CaseID)

## Study I

p1_sub_amce <- as.data.frame(cbind(
          round(p1_all_amce$estimate, digits = 3), round(p1_all_amce$std.error, digits = 3),
          round(p1_female_amce$estimate, digits = 3), round(p1_female_amce$std.error, digits = 3),
          round(p1_male_amce$estimate, digits = 3), round(p1_male_amce$std.error, digits = 3),
          round(p1_rural_amce$estimate, digits = 3), round(p1_rural_amce$std.error, digits = 3),
          round(p1_urban_amce$estimate, digits = 3), round(p1_urban_amce$std.error, digits = 3)))

p1_sub_amce$level <- p1_all_amce$level

names(p1_sub_amce) <- c('Estimate.a', 'SE.a', 'Estimate.f', 'SE.f',
                        'Estimate.m', 'SE.m', 'Estimate.r', 'SE.r',
                        'Estimate.u', 'SE.u', 'Level')

p1_sub_amce <- p1_sub_amce[, c(11, 1:10)]

p1_tab_amce_sub <- kable(p1_sub_amce, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1, "All Respondents" = 2, "Female Respondents" = 2,
                     "Male Respondents" = 2, "Rural Respondents" = 2,
                     "Urban Respondents" = 2)) %>%
  pack_rows("Education", 1, 4) %>%
  pack_rows("Political Experience", 5, 10) %>%
  pack_rows("Sex", 11, 12) %>%
  pack_rows("Race", 13, 17) %>%
  pack_rows("Religion", 18, 26) %>%
  pack_rows("Party Affiliation", 27, 29) %>%
  pack_rows("Car", 30, 34) %>%
  pack_rows("Hobbies", 35, 41) %>%
  pack_rows("Occupation", 42, 48) %>%
  pack_rows("Education Policy", 49, 51) %>%
  pack_rows("Global Warming", 52, 54)

## Study III

p4_sub <- as.data.frame(cbind(round(p4_all$estimate, digits = 3), round(p4_all$std.error, digits = 3), round(p4_sd$estimate, digits = 3), round(p4_sd$std.error, digits = 3), round(p4_sr$estimate, digits = 3), round(p4_sr$std.error, digits = 3)))

p4_sub$level <- p4_sd$level

names(p4_sub) <- c('Estimate.a', 'SE.a', 'Estimate.D', 'SE.D', 'Estimate.R', 'SE.R', 'Level')

p4_sub <- p4_sub[, c(7, 1:6)]

p4_tab_sub <- kable(p4_sub, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1, "All Respondents" = 2,
                    "Strong Democrats" = 2, "Strong Republicans" = 2)) %>%
  pack_rows("Party Affiliation", 1, 3) %>%
  pack_rows("Pipeline Stance", 4, 6) %>%
  pack_rows("Hobbies", 7, 9) %>%
  pack_rows("Car", 10, 12) %>%
  pack_rows("Restaurant", 13, 15)

# Congruence and Match

## Study I

m1_cong <- Chosen ~ Education + Experience + Gender + Race + Religion + PID + Car.Type + Hobbies + Occupation + Schools + Global.Warming + Congruence

m1_match <- Chosen ~ Education + Experience + Gender + Race + Religion + PID + Car.Type + Hobbies + Occupation + Schools + Global.Warming + Match

p1_d_cong <- mm(subset(df_cb, party < 0.5), m1_cong, id = ~CaseID)
p1_r_cong <- mm(subset(df_cb, party > 0.5), m1_cong, id = ~CaseID)

p1_d_match <- mm(subset(df_cb, party < 0.5), m1_match, id = ~CaseID)
p1_r_match <- mm(subset(df_cb, party > 0.5), m1_match, id = ~CaseID)

## Study III

m4_cong <- choice2 ~ Party + Pipeline + Hobbies + Car + Restaurant + Congruence
m4_match <- choice2 ~ Party + Pipeline + Hobbies + Car + Restaurant + Match

p4_d_cong <- mm(subset(dat4_l, PID < 3), m4_cong, id = ~CaseID)
p4_r_cong <- mm(subset(dat4_l, PID > 3), m4_cong, id = ~CaseID)
p4_d_match <- mm(subset(dat4_l, PID < 3), m4_match, id = ~CaseID)
p4_r_match <- mm(subset(dat4_l, PID > 3), m4_match, id = ~CaseID)

## Study I

p1_cm <- as.data.frame(cbind(
          round(p1_d_cong$estimate, digits = 3), round(p1_d_cong$std.error, digits = 3),
          round(p1_r_cong$estimate, digits = 3), round(p1_r_cong$std.error, digits = 3)))

p1_cm$level <- p1_d_cong$level

names(p1_cm) <- c('Estimate.d', 'SEd', 'Estimate.r', 'SE.r', 'Level')

p1_cm <- p1_cm[, c(5, 1:4)]

p1_tab_cm <- kable(p1_cm, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1, "Democrats" = 2, "Republicans" = 2)) %>%
  pack_rows("Education", 1, 4) %>%
  pack_rows("Political Experience", 5, 10) %>%
  pack_rows("Sex", 11, 12) %>%
  pack_rows("Race", 13, 17) %>%
  pack_rows("Religion", 18, 26) %>%
  pack_rows("Party Affiliation", 27, 29) %>%
  pack_rows("Car", 30, 34) %>%
  pack_rows("Hobbies", 35, 41) %>%
  pack_rows("Occupation", 42, 48) %>%
  pack_rows("Education Policy", 49, 51) %>%
  pack_rows("Global Warming", 52, 54) %>%
  pack_rows("Congruence", 55, 57)

p1_m <- as.data.frame(cbind(
          round(p1_d_match$estimate, digits = 3), round(p1_d_match$std.error, digits = 3),
          round(p1_r_match$estimate, digits = 3), round(p1_r_match$std.error, digits = 3)))

p1_m$level <- p1_d_match$level

names(p1_m) <- c('Estimate.d', 'SEd', 'Estimate.r', 'SE.r', 'Level')

p1_m <- p1_m[, c(5, 1:4)]

p1_tab_m <- kable(p1_m, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1, "Democrats" = 2, "Republicans" = 2)) %>%
  pack_rows("Education", 1, 4) %>%
  pack_rows("Political Experience", 5, 10) %>%
  pack_rows("Sex", 11, 12) %>%
  pack_rows("Race", 13, 17) %>%
  pack_rows("Religion", 18, 26) %>%
  pack_rows("Party Affiliation", 27, 29) %>%
  pack_rows("Car", 30, 34) %>%
  pack_rows("Hobbies", 35, 41) %>%
  pack_rows("Occupation", 42, 48) %>%
  pack_rows("Education Policy", 49, 51) %>%
  pack_rows("Global Warming", 52, 54) %>%
  pack_rows("Match", 55, 57)

## Study III

p4_cm <- as.data.frame(cbind(
          round(p4_d_cong$estimate, digits = 3), round(p4_d_cong$std.error, digits = 3),
          round(p4_r_cong$estimate, digits = 3), round(p4_r_cong$std.error, digits = 3)))

p4_cm$level <- p4_d_cong$level

names(p4_cm) <- c('Estimate.d', 'SE.d', 'Estimate.r', 'SE.r', 'Level')

p4_cm <- p4_cm[, c(5, 1:4)]

p4_tab_cm <- kable(p4_cm, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1,
                    "Democrats" = 2, "Republicans" = 2)) %>%
  pack_rows("Party Affiliation", 1, 3) %>%
  pack_rows("Pipeline Stance", 4, 6) %>%
  pack_rows("Hobbies", 7, 9) %>%
  pack_rows("Car", 10, 12) %>%
  pack_rows("Restaurant", 13, 15) %>%
  pack_rows("Congruence", 16, 18)

p4_m <- as.data.frame(cbind(
          round(p4_d_match$estimate, digits = 3), round(p4_d_match$std.error, digits = 3),
          round(p4_r_match$estimate, digits = 3), round(p4_r_match$std.error, digits = 3)))

p4_m$level <- p4_d_match$level

names(p4_m) <- c('Estimate.d', 'SE.d', 'Estimate.r', 'SE.r', 'Level')

p4_m <- p4_m[, c(5, 1:4)]

p4_tab_m <- kable(p4_m, format = "latex") %>%
  kable_classic() %>%
  add_header_above(c(" " = 1,
                    "Democrats" = 2, "Republicans" = 2)) %>%
  pack_rows("Party Affiliation", 1, 3) %>%
  pack_rows("Pipeline Stance", 4, 6) %>%
  pack_rows("Hobbies", 7, 9) %>%
  pack_rows("Car", 10, 12) %>%
  pack_rows("Restaurant", 13, 15) %>%
  pack_rows("Match", 16, 18)

```


